<?php

namespace App\Jobs\System;
// 加载采集环境

use App\Wen\Utils\SiteUtils;
use Dcat\Admin\Models\AdminSubMenu;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class SubMenuPermissionCheck implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        AdminSubMenu::all()->map(function ($v){
            global $__MINI_GLOBAL_TENANTS_ARR__;
            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANTS_ARR__){
                foreach ($__MINI_GLOBAL_TENANTS_ARR__ as $tenant_id){
                    if($tenant_id === 0){
                        continue;
                    }
                    if(!Schema::hasTable('admin_permission_menu_'.$tenant_id)) {
                        SiteUtils::forget_config_data();
                        continue;
                    }
                    $__MINI_GLOBAL_TENANT_ID__ = $tenant_id;
                    if(!(DB::table('admin_permission_menu_'.$tenant_id)->where('menu_id', $v->id)->exists())){
                        DB::beginTransaction();
                        try {
                            // todo:
                            $perssion_name = $v->title;
                            if($v->parent_id && $v->parent_id > 0){
                                $menu_father = AdminSubMenu::find($v->parent_id);
                                if($menu_father){
                                    $perssion_name = $menu_father->title.'-' . $perssion_name;
                                    if($menu_father->parent_id && $menu_father->parent_id > 0){
                                        $menu_gurand_father = AdminSubMenu::find($menu_father->parent_id);
                                        if($menu_gurand_father){
                                            $perssion_name = $menu_gurand_father->title.'-' . $perssion_name;
                                        }
                                    }
                                }
                            }


                            $http_path = $v->uri.'*';
                            foreach (['settings', 'realtime'] as $special){
                                if(strpos($v->uri, $special.'/') !== false){
                                    $uri_arr = explode('/', $v->uri);
                                    if(count($uri_arr) == 2){
                                        $http_path .= ',/'. $uri_arr[0].'/action/'.$uri_arr[1];
                                    }else if(count($uri_arr) == 3){
                                        if(_empty_($uri_arr[0])){
                                            $http_path .= ',/'. $uri_arr[1].'/action/'.$uri_arr[2];
                                        }
                                    }
                                }
                            }

                            foreach (['config'] as $special){
                                if(strpos($v->uri, '/'.$special) !== false){
                                    $uri_arr = explode('/', $v->uri);
                                    if(count($uri_arr) == 2){
                                        $http_path .= ',/'. $uri_arr[0].'/action/'.$uri_arr[1];
                                    }else if(count($uri_arr) == 3){
                                        if(_empty_($uri_arr[0])){
                                            $http_path .= ',/'. $uri_arr[1].'/action/'.$uri_arr[2];
                                        }
                                    }
                                }
                            }

                            if(DB::table('admin_permissions_'.$tenant_id)->where('http_path','like', '%'. $http_path .'%')->exists()){

                                $currentTimestamp = Carbon::now();
                                $permission_id = DB::table('admin_permissions_'.$tenant_id)->where('http_path','like', '%'. $http_path .'%')->value('id');
                                if(!(DB::table('admin_permission_menu_'.$tenant_id)->where('permission_id', $permission_id)->where('menu_id', $v->id)->exists())){
                                    DB::table('admin_permission_menu_'.$tenant_id)->insert([
                                        'permission_id' => $permission_id,
                                        'menu_id' => $v->id,
                                        'updated_at' => $currentTimestamp,
                                        'created_at' => $currentTimestamp,
                                    ]);
                                }

                            }else{

                                $currentTimestamp = Carbon::now();
                                DB::table('admin_permissions_'.$tenant_id)->insert([
                                    'name' => $perssion_name,
                                    'slug' => str_replace('/', '_', $http_path),
                                    'http_method' => null,
                                    'http_path' => $http_path,
                                    'order' => 47,
                                    'parent_id' => 0,
                                    'updated_at' => $currentTimestamp,
                                    'created_at' => $currentTimestamp,
                                ]);
                                $p_id = DB::table('admin_permissions_'.$tenant_id)->where('http_path',$http_path)->value('id');
                                // 插入数据到 example_table 表
                                if(!(DB::table('admin_permission_menu_'.$tenant_id)->where('permission_id', $p_id)->where('menu_id', $v->id)->exists())){
                                    DB::table('admin_permission_menu_'.$tenant_id)->insert([
                                        'permission_id' => $p_id,
                                        'menu_id' => $v->id,
                                        'updated_at' => $currentTimestamp,
                                        'created_at' => $currentTimestamp,
                                    ]);
                                }
                            }

                            DB::commit();
                            return true;
                        } catch (\Exception $e) {
                            DB::rollBack();
                            _logger_(__file__, __line__, $e->getMessage());
                            return false;
                        }
                    }
                }
            }
        });
    }
}

